#include <libavutil/log.h>
#include <libavutil/timestamp.h>
#include <libavformat/avformat.h>

int main(int argc, char *argv[])
{
    AVFormatContext *ifmt_ctx = NULL;
    AVFormatContext *ofmt_ctx = NULL;
    const char *in_filename, *out_filename;
    int ret = 0;
    int stream_mapping_size = 0;
    int *stream_mapping = NULL;
    AVOutputFormat *ofmt = NULL;
    int i;
    int stream_index = 0;
    AVPacket pkt;
    av_log_set_level(AV_LOG_INFO);

    if (argc < 3)
    {
        av_log(NULL, AV_LOG_ERROR, "usage: %s input output\n"
                                   "API example program to remux a media file with libavformat and libavcodec.\n"
                                   "The output format is guessed according to the file extension.\n"
                                   "\n",
               argv[0]);
        return 1;
    }
    in_filename = argv[1];
    out_filename = argv[2];

    //第一步 打开输入文件，获取文件上下文
    ret = avformat_open_input(&ifmt_ctx,
                              in_filename,
                              NULL,
                              NULL);
    if (ret < 0)
    {
        goto __ERROR;
    }
    ret = avformat_find_stream_info(ifmt_ctx, NULL);
    if (ret < 0)
    {
        av_log(NULL, AV_LOG_ERROR, "Failed to retrieve input stream information");
        goto __ERROR;
    }

    av_dump_format(ifmt_ctx, 0, in_filename, 0);

    //第二步 创建输出文件上下文
    avformat_alloc_output_context2(&ofmt_ctx,
                                   NULL,
                                   NULL,
                                   out_filename);
    if (!ofmt_ctx)
    {
        av_log(NULL, AV_LOG_ERROR, "Could not create output context\n");
        ret = AVERROR_UNKNOWN;
        goto __ERROR;
    }

    //第三步 为输出文件上下文创建视频 音频 字幕流

    //stream_mapping记录视频、音频、字幕流的索引
    stream_mapping_size = ifmt_ctx->nb_streams;
    stream_mapping = av_mallocz_array(stream_mapping_size, sizeof(*stream_mapping));
    if (!stream_mapping)
    {
        ret = AVERROR(ENOMEM);
        goto __ERROR;
    }

    ofmt = ofmt_ctx->oformat;
    for (i = 0; i < ifmt_ctx->nb_streams; i++)
    {
        AVStream *out_stream;
        AVStream *in_stream = ifmt_ctx->streams[i];
        AVCodecParameters *in_codecpar = in_stream->codecpar;

        if (in_codecpar->codec_type != AVMEDIA_TYPE_AUDIO &&
            in_codecpar->codec_type != AVMEDIA_TYPE_VIDEO &&
            in_codecpar->codec_type != AVMEDIA_TYPE_SUBTITLE)
        {
            stream_mapping[i] = -1;
            continue;
        }

        stream_mapping[i] = stream_index++;

        out_stream = avformat_new_stream(ofmt_ctx, NULL);
        if (!out_stream)
        {
            av_log(NULL, AV_LOG_ERROR, "Failed allocating output stream\n");
            ret = AVERROR_UNKNOWN;
            goto __ERROR;
        }

        ret = avcodec_parameters_copy(out_stream->codecpar, in_codecpar);
        if (ret < 0)
        {
            av_log(NULL, AV_LOG_ERROR, "Failed to copy codec parameters\n");
            goto __ERROR;
        }
        out_stream->codecpar->codec_tag = 0;
    }

    av_dump_format(ofmt_ctx, 0, out_filename, 1);

    av_init_packet(&pkt);
    pkt.size = 0;
    pkt.data = NULL;

    //第四步 创建输出文件IO上下文
    if (!(ofmt->flags & AVFMT_NOFILE))
    {
        ret = avio_open(&ofmt_ctx->pb, out_filename, AVIO_FLAG_WRITE);
        if (ret < 0)
        {
            av_log(NULL, AV_LOG_ERROR, "Could not open output file '%s'", out_filename);
            goto __ERROR;
        }
    }

    //第五步 写输出文件头
    ret = avformat_write_header(ofmt_ctx, NULL);

    //第六步 读取输入文件读出AVPacket，设置正确的stream_index,设置pts，dts，duraction并将packet写入输出文件
    while (1)
    {
        AVStream *in_stream, *out_stream;
        ret = av_read_frame(ifmt_ctx, &pkt);
        if (ret < 0)
            break;
        in_stream = ifmt_ctx->streams[pkt.stream_index];

        //判断当前流是否是需要提取的流
        if (pkt.stream_index >= stream_mapping_size || stream_mapping[pkt.stream_index] < 0)
        {
            av_packet_unref(&pkt);
            continue;
        }

        pkt.stream_index = stream_mapping[pkt.stream_index];
        out_stream = ofmt_ctx->streams[pkt.stream_index];

        pkt.pts = av_rescale_q_rnd(pkt.pts, in_stream->time_base, out_stream->time_base, AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX);
        pkt.dts = av_rescale_q_rnd(pkt.dts, in_stream->time_base, out_stream->time_base, AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX);
        pkt.duration = av_rescale_q(pkt.duration, in_stream->time_base, out_stream->time_base);
        pkt.pos = -1;

        ret = av_interleaved_write_frame(ofmt_ctx, &pkt);
        av_packet_unref(&pkt);

        if (ret < 0)
        {
            av_log(NULL, AV_LOG_ERROR, "Error muxing packet\n");
            break;
        }
    }

    //第七步 写文件尾
    av_write_trailer(ofmt_ctx);
    av_log(NULL, AV_LOG_ERROR, "remux success \n");
    av_dump_format(ofmt_ctx, 0, out_filename, 1);

__ERROR:
    //第八步 释放资源
    if (ifmt_ctx)
    {
        avformat_close_input(&ifmt_ctx);
        avformat_free_context(ifmt_ctx);
    }

    if (ofmt_ctx && !(ofmt->flags & AVFMT_NOFILE))
    {
        avio_closep(&ofmt_ctx->pb);
    }
    if (ofmt_ctx)
    {
        avformat_free_context(ofmt_ctx);
    }
    if (stream_mapping)
    {
        av_freep(&stream_mapping);
    }

    return ret;
}